package test.echarts.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class DaqicengController {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public DaqicengController(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @GetMapping("/temperature-data4")
    public Map<String, Object> getTemperatureData() {
        String query = "SELECT week_start_date, AVG(monday) AS monday_avg, AVG(tuesday) AS tuesday_avg, AVG(wednesday) AS wednesday_avg, AVG(thursday) AS thursday_avg, AVG(friday) AS friday_avg, AVG(saturday) AS saturday_avg, AVG(sunday) AS sunday_avg FROM qiweibiao GROUP BY week_start_date";
        List<Map<String, Object>> result = jdbcTemplate.queryForList(query);

        List<String> weekStartDates = new ArrayList<>();
        List<Double> averageTemperatures = new ArrayList<>();

        for (Map<String, Object> row : result) {
            weekStartDates.add(row.get("week_start_date").toString());
            double averageTemperature = (Double.parseDouble(row.get("monday_avg").toString()) +
                    Double.parseDouble(row.get("tuesday_avg").toString()) +
                    Double.parseDouble(row.get("wednesday_avg").toString()) +
                    Double.parseDouble(row.get("thursday_avg").toString()) +
                    Double.parseDouble(row.get("friday_avg").toString()) +
                    Double.parseDouble(row.get("saturday_avg").toString()) +
                    Double.parseDouble(row.get("sunday_avg").toString())) / 7.0;

            // 保留2位小数
            BigDecimal roundedTemperature = BigDecimal.valueOf(averageTemperature).setScale(2, RoundingMode.HALF_UP);
            averageTemperatures.add(roundedTemperature.doubleValue());
        }

        Map<String, Object> data = new HashMap<>();
        data.put("weekStartDates", weekStartDates);
        data.put("averageTemperatures", averageTemperatures);

        return data;
    }
}